/**
 * Copyright 2007 Jason Horman, Pete Aykroyd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.functor.expression;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * And's a number of {@link org.functor.UnaryPredicate unary predicates} together. Short
 * circuits, meaning the first false stops the test.
 */
public class AndImpl extends AbstractJunction implements And {
	public AndImpl() {
		this(new ArrayList<PredicateExpression>());
	}

	public AndImpl(PredicateExpression ... predicates) {
		this(Arrays.asList(predicates));
	}

	public AndImpl(List<PredicateExpression> preds) {
		super(optimizePredicates(preds));
	}

	public AndImpl(Collection<PredicateExpression> predicates) {
		this(new ArrayList(predicates));
	}

	public boolean isAlwaysTrue() {
		for (PredicateExpression expression : getPredicates())
			if (!expression.isAlwaysTrue())
				return false;
		return true;
	}

	public boolean isAlwaysFalse() {
		for (PredicateExpression expression : getPredicates())
			if (expression.isAlwaysFalse())
				return true;
		return false;
	}

	protected String getJoiningKeyword() {
		return " AND ";
	}

	private static List<PredicateExpression> optimizePredicates(List<PredicateExpression> preds) {
		List optimized = new ArrayList();
		for (PredicateExpression predicate : preds) {
			if (predicate == null)
				continue;
			if (predicate instanceof And)
				optimized.addAll(((And) predicate).getPredicates());
			else if (!predicate.isAlwaysTrue())
				optimized.add(predicate);
		}

		return optimized;
	}
}
